package com.szbmyoubao.app.view.dialog

import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.helper.DownloadManager
import com.szbmyoubao.app.utils.SaveUtils
import com.ellecity06.common.base.BaseDialogFragment
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.databinding.DialogDownVideoBinding

/**
 * @author ellecity06
 * @time 2024/12/25 11:33
 * @des 下载视频
 */
fun FragmentActivity.downVideo(url: String, title: String? = null) {
    DownLoadVideoDialog.newInstance(url, title).show(supportFragmentManager, "DownLoadVideoDialog")
}


class DownLoadVideoDialog : BaseDialogFragment<DialogDownVideoBinding>() {
    private val videoUrl: String by lazy { arguments?.getString("url") ?: "" }
    override val isTouchOutsideDismiss: Boolean
        get() = false
    companion object {
        fun newInstance(url: String, title: String?): DownLoadVideoDialog {
            val args = Bundle()
            args.apply {
                putString("title", title)
                putString("url", url)
            }
            val f = DownLoadVideoDialog()
            f.arguments = args
            return f
        }
    }

    override fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): DialogDownVideoBinding {
        return DialogDownVideoBinding.inflate(layoutInflater, container, false)
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        logD("下载弹窗消失")
    }

    override fun initialize() {
        lifecycleScope.launchWhenCreated {
            DownloadManager.Companion.download(videoUrl).collect {
                when (it) {
                    is DownloadState.Error -> {
                        logD("", tr = it.throwable)
                        ToastUtils.show("下载失败请稍后重试")
                        dismiss()
                    }

                    is DownloadState.InProgress -> {
                        binding.pb.setProgress(it.progress.toFloat())
                    }

                    is DownloadState.Success -> {
                        SaveUtils.saveVideoToAlbum(requireActivity(), it.file.absolutePath)
                        ToastUtils.show("下载成功")
                        dismiss()
                    }
                }
            }
        }

    }

}